package com.tgy.controller;

import com.tgy.entity.Dept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/***
 * @ClassName: ConsumerController
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 9:46 2022/1/11
 * @version : V1.0
 */
@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {
    /**
     * 消费者不该有Service层应该由Provider提供
     * RestTemplate .... 供我们直接调用就可以了！ 注册到Spring中
     * (地址：url, 实体：Map ,Class<T> responseType)
     * <p>
     * 提供多种便捷访问远程http服务的方法，简单的Restful服务模板~
     */
    @Resource(name = "getRestTemplate")
    RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;
    /**
     * 服务提供方地址前缀
     * <p>
     * Ribbon:我们这里的地址，应该是一个变量，通过服务名来访问
     */
    //private static final String REST_URL_PREFIX = "http://localhost:8001";
    private static final String REST_URL_PREFIX = "http://ProviderDept01";

    public  String url(){
        List<ServiceInstance> instances =discoveryClient.getInstances("ProviderDept01");
        StringBuilder urls= new StringBuilder();
        for(ServiceInstance instance : instances){
            urls.append(instance.getHost()+":"+instance.getPort());
        }

        log.info("地址是{}","http://"+ urls);
        return "http://"+ urls;
    }

    @RequestMapping("/test")
    public String test() {
        String url = url();
        log.info("controller地址是{}",url);
        return restTemplate.getForObject(url+"/test",String.class);
    }
    @PostMapping("/list")
    public List<Dept> list(@RequestBody Dept dept) {
        return restTemplate.postForObject(REST_URL_PREFIX+"/getEntity",dept,List.class);
    }

    @PostMapping("/add")
    public Boolean add(@RequestBody Dept dept){
        return restTemplate.postForObject(REST_URL_PREFIX +"/add",dept,Boolean.class);
    }

    @PostMapping("/upd")
    public Boolean upd(@RequestBody Dept dept){
        return restTemplate.postForObject(REST_URL_PREFIX+"/upd",dept,Boolean.class);

    }
    @GetMapping("/delR/{id}")
    public Integer delR(@PathVariable(name = "id", required = true) Long id ){
        return restTemplate.getForObject(REST_URL_PREFIX+"/delR/"+id,Integer.class);
    }
    @GetMapping("/del")
    public Integer del(@RequestParam(name ="id") Long id ){
        return restTemplate.getForObject(REST_URL_PREFIX+"/del",Integer.class,id);
    }
}
